<script>
export default {
  name: "PetManage",
  data() {
    return {
      tableData: [],
      pageSize: 5,
      pageNum: 1,
      total: 0,
      keywords:'',
      imageUrl: '',
      centerDialogVisible:false,
      form: {
        id: '',
        petNo: '',
        petName: '',
        status: '',
        petType: '',
        content:'',
        sex: '',
        createTime:'',
        imageFile: null
      },
      rules: {
        petNo: [{ required: true, message: '请输入宠物编号', trigger: 'blur' }],
        petName: [{ required: true, message: '请输入宠物名称', trigger: 'blur' }],
        petType: [{ required: true, message: '请选择宠物类别', trigger: 'change' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        content: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      }
    };
  },
  methods: {
    loadPost() {
      this.$axios.post(this.$httpUrl + '/pet/listPageP', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        param: { keywords: this.keywords }
      }).then(res=>res.data).then(res => {
        if (res.code === 200)
        {
          this.tableData = res.data;
          this.total = res.total;
        }else{
          alert('获取数据失败')
        }
      });
    },
    add(){//打开表单
      this.loadPost();
      this.centerDialogVisible = true
      this.$nextTick(()=>{
        this.resetForm();
      })
    },
    mod(row){////"编辑"按钮方法:赋值到表单
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        this.form = {
          id: row.id, // 确保id为字符串
          petNo: row.petNo,
          petName: row.petName,
          petType: row.petType,
          sex: row.sex,
          status: row.status,
          applyStatus: row.applyStatus,
          content: row.content,
          createTime: row.createTime || new Date().toISOString(),
          petImage:'',
          imageFile: null
        };
        this.imageUrl = row.id ? `${this.$httpUrl}/pet/image/${row.id}?t=${new Date().getTime()}` : '';
      });
    },
    resetParam(){
      this.keywords = ''
      this.loadPost()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    // 新增/保存
    save(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id){
            this.doMod();
          }else {
            this.doSave();
          }
        } else {
          this.$message.error('请填写完整表单！');
          return false;
        }
      });
    },
    doMod(){//更新
      const formData = new FormData();
      formData.append('id', this.form.id);
      formData.append('petNo', Number(this.form.petNo));
      formData.append('petName', this.form.petName);
      formData.append('petType', Number(this.form.petType));
      formData.append('sex', Number(this.form.sex));
      formData.append('status', Number(this.form.status));
      formData.append("applyStatus", this.form.applyStatus);
      formData.append('content', this.form.content);
      formData.append('createTime' ,this.formatDateTime(this.form.createTime) || '');
      if (this.form.imageFile) {
        formData.append('imageFile', this.form.imageFile);
      }
      this.$axios.post(this.$httpUrl + '/pet/update', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => res.data).then(res => {
        if (res.code === 200) {
          this.$message.success('更新成功！');
          this.centerDialogVisible = false;
          this.loadPost();
        } else {
          this.$message.error(res.data.msg || '更新失败！');
        }
      }).catch(error => {
        console.error('更新请求失败:', error);
        this.$message.error('请求异常，请检查控制台');
      });
    },
    doSave(){//新增
      const formData = new FormData();
      // 添加所有表单字段
      formData.append('petNo', Number(this.form.petNo));
      formData.append('petName', this.form.petName);
      formData.append('petType', Number(this.form.petType));
      formData.append('sex', Number(this.form.sex));
      formData.append('status', Number(this.form.status));
      formData.append("applyStatus", this.form.applyStatus);
      formData.append('content', this.form.content);
      formData.append('createTime' ,this.formatDateTime(this.form.createTime) || '');
      if (this.form.imageFile) {
        formData.append('imageFile', this.form.imageFile);
      }
      this.$axios.post(this.$httpUrl + '/pet/save', formData, {
        headers: {
          'Content-Type': 'multipart/form-data' //设置FormData的Content-Type
        }
      }).then(res => res.data).then(res => {
        if (res.code === 200) {
          this.$message.success(' 新增成功！');
          this.centerDialogVisible = false;
          this.loadPost();
        } else {
          this.$message.error(res.data.msg || '新增失败！');
        }
      });
    },
    del(id){//"删除"按钮方法
      this.$axios.get(this.$httpUrl + `/pet/del?id=${id}`).then(res => {
        if (res.data.code === 200) {
          this.$message.success('删除成功！');
          this.loadPost();
        } else {
          this.$message.error('删除失败！');
        }
      }).catch(error => {
        console.error('删除请求失败:', error);
        this.$message.error('请求异常，请检查控制台');
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    formatDateTime(date) {
      if (!date) return ''; // 处理空值
      try {
        const d = new Date(date);
        // 检查是否为有效日期
        if (isNaN(d.getTime())) return '';
        return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`;
      } catch (e) {
        console.error('日期格式化失败:', e);
        return '';
      }
    },
    handleImageChange(file) {
      this.form.imageFile = file.raw;
      this.imageUrl = URL.createObjectURL(file.raw); // 本地预览
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    formatId(id) {
      return id.toString().slice(-6); // 显示后6位
    }
  },
  beforeMount() {
    this.loadPost();
  }
};
</script>

<template>
  <div>
    <div style="border-bottom: 5px">
      <el-input v-model="keywords" placeholder="宠物编号/宠物名称..." suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
    </div>
    <!-- 表格列为宠物字段 -->
    <el-table :data="tableData" :header-cell-style="{background:'#d2bcad'}"
              border>
      <el-table-column prop="id" label="ID" width="50">
        <template slot-scope="{ row }">
          {{ formatId(row.id) }}
        </template>
      </el-table-column>
      <el-table-column prop="petNo" label="宠物编号" width="80">
      </el-table-column>
      <el-table-column prop="petName" label="宠物名称" width="80">
      </el-table-column>
      <el-table-column prop="petType" label="宠物类别" width="80">
        <template slot-scope="{ row }">
          <el-tag :type="row.petType === 4 ? 'primary' : 'success'">
            {{ row.petType === 4 ? '狗狗' : '猫猫' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="宠物性别" width="80">
        <template slot-scope="{ row }">
          <el-tag :type="row.sex === 1 ? 'primary' : 'success'">
            {{ row.sex === 1 ? 'male' : 'female' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="宠物状态" width="80">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 200 ? 'success' : 'danger'">
            {{ row.status === 200 ? '健康' : '疾病' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applyStatus" label="领养状态" width="80">
        <template slot-scope="{ row }">
          <el-tag :type="row.applyStatus === 1 ? 'success' : row.applyStatus === 0 ? 'warning' : 'info'">
            {{
              row.applyStatus === 0 ? '已申请' :
                  row.applyStatus === 1 ? '已领养' :
                      '未领养'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="详细描述" >
      </el-table-column>
      <el-table-column prop="createTime" label="记录时间" width="90">
      </el-table-column>
      <el-table-column prop="operator" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              confirm-button-text='好的'
              confirm-button-type="warning"
              cancel-button-text='不用了'
              icon="el-icon-info"
              icon-color="red"
              title="该操作不可逆,确定删除吗? "
              @confirm="del(scope.row.id)"
              style="margin-left: 5px">
            <el-button slot="reference" size="small" type="danger" >删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <el-form ref="form" :rules="rules"
               :model="form"
               label-width="80px"
               style="display: table-caption">
        <el-form-item label="宠物图片">
          <el-upload
              action="#"
              :auto-upload="false"
              :on-change="handleImageChange"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">仅支持 JPG/PNG 文件，不超过2MB</div>
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="max-width: 200px; margin-top: 10px;" />
          </el-upload>
        </el-form-item>
        <el-form-item label="宠物编号" prop="petNo">
          <el-col :span="20">
            <el-input v-model="form.petNo"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="宠物名称" prop="petName">
          <el-col :span="20">
            <el-input v-model="form.petName"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="宠物类别" prop="petType">
          <el-select v-model="form.petType">
            <el-option label= "狗狗" :value="4" />
            <el-option label= "猫猫" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="宠物性别" prop="sex">
          <el-col :span="20">
            <el-radio-group v-model="form.sex">
              <el-radio :label="1">male</el-radio>
              <el-radio :label="6">female</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="宠物状态" prop="status">
          <el-select v-model="form.status">
            <el-option label= "健康" :value="200" />
            <el-option label= "疾病" :value="400" />
          </el-select>
        </el-form-item>
        <el-form-item label="领养状态" prop="applyStatus">
          <el-select v-model="form.applyStatus">
            <el-option label="已申请" :value="0" />
            <el-option label="已领养" :value="1" />
            <el-option label="未领养" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细描述" prop="content">
          <el-col :span="20">
            <el-input v-model="form.content"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="记录时间">
          <el-date-picker
              v-model="form.createTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>